package de.eridea.learning.usermanagement.webinterface;

import de.eridea.learning.java.usermanagement.logic.UserService;
import de.eridea.learning.java.usermanagement.logic.exception.NoSuchUserException;
import de.eridea.learning.java.usermanagement.logic.exception.VerificationFailedException;
import de.eridea.learning.java.usermanagement.logic.to.UserData;

public class ChangePasswordHandler {
	private UserBean userBean;
	private UserService userService;
	
	private String pwd1;
	private String pwd2;
	private String oldPwd;
	
	public String changePassword() {
		if(userBean == null) {
			throw new IllegalStateException("userBean is null");
		}
		if(userService == null) {
			throw new IllegalStateException("userService is null");
		}
		String result = null;
		try {
			UserData user = userService.login(userBean.getLoginName(), oldPwd);
			if (pwd1.equals(pwd2)) {
				userService.updateUserPassword(user.getLoginName(), pwd1);
			}
			result = "user-settings";
		} catch (VerificationFailedException e) {
			result = "wrong-pwd";
		} catch (NoSuchUserException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		pwd1 = null;
		pwd2 = null;
		return result;
	}
	
	public UserBean getUserBean() {
		return userBean;
	}
	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}
	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getPwd1() {
		return pwd1;
	}

	public void setPwd1(String pwd1) {
		this.pwd1 = pwd1;
	}

	public String getPwd2() {
		return pwd2;
	}

	public void setPwd2(String pwd2) {
		this.pwd2 = pwd2;
	}

	public String getOldPwd() {
		return oldPwd;
	}

	public void setOldPwd(String oldPwd) {
		this.oldPwd = oldPwd;
	}
}
